import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { UserService } from 'src/module/user/user.service';
import { Request } from 'express';
import { CustomException, ErrorCode } from 'src/common/exceptions/custom.exception';
import { JwtCustomPayload } from 'src/types';
import { JwtConfigService } from 'src/module/jwt/jwt.config.service';
import { RedisService } from 'src/module/redis/redis.service';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly userService: UserService,
    private readonly jwtConfigService: JwtConfigService,
    private readonly redisService: RedisService,
    private readonly configService: ConfigService,
  ) {
    super({
      // 指定以何种方式提取令牌
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      // 解析令牌秘钥"d0!doc15415B0*4G0`"
      secretOrKey: process.env.JWT_SECRET || configService.get('JWT_SECRET'),
      // 是否忽略令牌过期
      ignoreExpiration: false,
      // 是否将请求对象作为回调函数第一个参数传递
      passReqToCallback: true,
    });
  }

  /** 验证成功的回调函数 */
  async validate(req: Request, payload: JwtCustomPayload) {
    const user = await this.userService.findByUsername(payload.username);
    // 验证用户是否禁用
    if (!user.enable) {
      throw new CustomException(ErrorCode.ERR_11007);
    }
    // 验证用户角色
    const currentRole = user.roles.find((item) => item.code === payload.currentRoleCode);
    if (!currentRole.enable) {
      throw new CustomException(ErrorCode.ERR_11008);
    }

    // 从请求头中获取token
    const reqToken = `Bearer ${ExtractJwt.fromAuthHeaderAsBearerToken()(req)}`;
    // 从 redis 获取token
    const redisTokenKey = this.jwtConfigService.getAccessTokenKey(payload.userId);
    const redisToken = await this.redisService.getString(redisTokenKey);
    // 判断令牌
    if (reqToken !== redisToken) {
      this.redisService.delString(redisTokenKey);
      throw new HttpException(ErrorCode.ERR_11002, HttpStatus.UNAUTHORIZED);
    }

    return {
      userId: payload.userId,
      username: payload.username,
      roleCodes: payload.roleCodes,
      currentRoleCode: payload.currentRoleCode,
    };
  }
}
